package com.laikan.reader.bookstart.activity;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.CountDownTimer;
import android.telephony.TelephonyManager;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import cn.sharesdk.framework.ShareSDK;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.laikan.library.components.activitys.BasicActivity;
import com.laikan.library.httpvolley.engine.HttpApiRequestEngine;
import com.laikan.library.httpvolley.engine.Requester;
import com.laikan.library.httpvolley.helper.RequestListener;
import com.laikan.library.httpvolley.helper.VolleyErrorHandler;
import com.laikan.library.httpvolley.response.HttpResponse;
import com.laikan.library.managers.ToastMgr;
import com.laikan.library.utils.DeviceUtil;
import com.laikan.library.utils.SPUtil;
import com.laikan.reader.R;
import com.laikan.reader.apirequester.BookShelfRequester;
import com.laikan.reader.comment.APIProtocol;
import com.laikan.reader.comment.Constants;
import com.laikan.reader.core.bean.BaseDataBean;
import com.laikan.reader.core.utils.AccountManager;
import com.laikan.reader.core.utils.LoadingDialog;
import com.laikan.reader.core.utils.PublicUtil;
import com.laikan.reader.database.Book;
import com.laikan.reader.database.db.DAO;
import com.socks.library.KLog;
import com.umeng.analytics.MobclickAgent;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * 登录页
 *
 * @author wxl
 */
public class GuideLoginActivity extends BasicActivity implements View.OnClickListener {

    private Button login_btn;
    /**
     * 标题栏
     */
    Drawable drawable_back_tv;
    private ImageView back_tv;
    private EditText name, password;
    private String mPassword;
    private TelephonyManager tm;
    /**
     * 登出操作对应的listener
     */
    private String thirdtype = "1";
    // 书架缓存列表
    private ArrayList<Book> cacheBookList;
    private int reqLogin = 1;
    private DAO dao;
    private boolean isChapterRefer = false;
    private RelativeLayout back_layout;
    private TextView mButton;
    private LoadingDialog mloadingDialog;
    CountDownTimerUtils mCountDownTimerUtils;

    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void assignViews() {
        setContentView(R.layout.lk_login_new1);
        ShareSDK.initSDK(this);
        name = (EditText)findViewById(R.id.name);
        password = (EditText)findViewById(R.id.password);
        login_btn = (Button)findViewById(R.id.login_btn);
        back_tv = (ImageView)findViewById(R.id.iv_back);
        back_layout = (RelativeLayout)findViewById(R.id.back_layout);
        mButton = (TextView)findViewById(R.id.tv_yanzheng);
    }

    @SuppressWarnings ("static-access")
    @Override
    protected void initData() {
        dao = new DAO(mContext);
        mloadingDialog = new LoadingDialog(mContext);
        //        name.setText(SPUtil.getString("user_name_temp", ""));
        isChapterRefer = getIntent().getBooleanExtra("isChapterRefer", false);
        tm = (TelephonyManager)getSystemService(mContext.TELEPHONY_SERVICE);
        drawable_back_tv = new BitmapDrawable(PublicUtil.getAlphaBitmap(PublicUtil.readBitMap(mContext, R.drawable.lk_back_small), Color.parseColor("#FFFFFF")));
        back_tv.setImageDrawable(drawable_back_tv);
    }

    @Override
    protected void setListener() {
        login_btn.setOnClickListener(this);
        back_layout.setOnClickListener(this);
        mButton.setOnClickListener(this);
        name.setOnFocusChangeListener(new OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    InputMethodManager imm = ((InputMethodManager)getSystemService(INPUT_METHOD_SERVICE));
                    imm.hideSoftInputFromWindow(name.getWindowToken(), 0);
                }
            }
        });
        password.setOnFocusChangeListener(new OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    InputMethodManager imm = ((InputMethodManager)getSystemService(INPUT_METHOD_SERVICE));
                    imm.hideSoftInputFromWindow(password.getWindowToken(), 0);
                    //                    password.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                }
            }
        });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_yanzheng:
                if (DeviceUtil.isMobileNO(name.getText().toString().trim())) {
                    mCountDownTimerUtils = new CountDownTimerUtils(mButton, 60000, 1000);
//                    mCountDownTimerUtils.start();
                    getYanZhengMa();
                }else {
                    ToastMgr.showShortToast("手机号无效！");
                }
                break;
            case R.id.back_layout:            //返回键
                name.clearFocus();
                password.clearFocus();
                finish();
                break;
            case R.id.login_btn:        // 普通登录
                MobclickAgent.onEvent(mContext, "lk_login_new");
                mPassword = password.getText().toString().trim();
                if (DeviceUtil.isMobileNO(name.getText().toString().trim())) {
                    if (mPassword.equals("")) {

                        ToastMgr.showShortToast(R.string.login_yanzheng_is_not_empty);
                    }else {

                        UserLogin();
                    }
                }else {
                    ToastMgr.showShortToast(R.string.login_phone_number_invalid);
                }
                break;
        }
    }

    private void getYanZhengMa() {
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("mobile", name.getText().toString().trim());  //手机号
        map.put("deviceId", tm.getDeviceId()); //设备号
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() { KLog.e("---------volley onPreExecute!!!"); }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                if (httpResponse == null || httpResponse.responseContent == null) {
                    return;
                }

                BaseDataBean result;
                Gson gson = new Gson();
                Type type = new TypeToken<BaseDataBean>() {}.getType();
                try {
                    result = gson.fromJson(httpResponse.responseContent, type);
                    if (result != null) {
                        if (result.getError_no().equals("704")) {
//                            mCountDownTimerUtils = new CountDownTimerUtils(mButton, 60000, 1000);
                            mCountDownTimerUtils.start();
                            ToastMgr.showShortToast(R.string.login_yanzheng_send);
                        } else {
                            mCountDownTimerUtils.onFinish();
                            ToastMgr.showShortToast(result.getError_msg());
                        }
                    }
                }catch (Exception e) {
                    mCountDownTimerUtils.onFinish();
                    ToastMgr.showShortToast(R.string.laikan_data_load_failed);
                    e.printStackTrace();
                }finally {
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                mCountDownTimerUtils.onFinish();
                ToastMgr.showShortToast(R.string.laikan_network_anomaly);
            }

            @Override
            public void onFinish() {

            }
        };

        Requester requester = new Requester();
        requester.setUrl(APIProtocol.getRootURL() + "accounts/logincode");
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);

//        HttpApiRequestEngine.getInstance().httpPostRequest(APIProtocol.getRootURL() + "accounts/logincode", map, null, null, requestListener);
    }

    private void UserLogin() {
        mloadingDialog.show();
        mPassword = password.getText().toString().trim();
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("mobile", name.getText().toString().trim());
        map.put("code", mPassword);
        map.put("deviceId", tm.getDeviceId());
        map.put("ua", android.os.Build.MODEL);
        if ("6".equals(thirdtype)) {
            map.put("unionId", SPUtil.getString("unionid", ""));
        }
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() { KLog.e("---------volley onPreExecute!!!"); }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                mloadingDialog.dismiss();
                try {
                    JSONObject obj = new JSONObject(httpResponse.responseContent);
                    KLog.i("", obj.toString());
                    int result_code = obj.optInt("result");
                    if (Constants.RESULT_OK.equals(result_code + "")) {
                        JSONObject data = obj.getJSONObject("data");
                        if(AccountManager.getInstance().isSwitchAccount(data.getString("token"))){
                            if(!TextUtils.isEmpty(SPUtil.getString("token", ""))){
                                AccountManager.getInstance().clearAccountData();
                            }
                        }
                        SPUtil.putString("token", data.getString("token"));
                        SPUtil.putString("user_id", data.getString("id"));
                        SPUtil.putString("user_name", data.getString("name"));
                        SPUtil.putString("user_score", data.getString("score"));
                        SPUtil.putString("user_level", data.getString("level"));
                        SPUtil.putString("user_icon", data.getString("icon"));
                        ToastMgr.showShortToast(R.string.login_success);
                        MobclickAgent.onEvent(mContext,"mobile_num_login");
                        MobclickAgent.onEvent(mContext,"laikan_login_count");
                        //(LoginActivity是当前的Activity)
                        ((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(GuideLoginActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                        SPUtil.putBoolean("switch_account", true);
                        SPUtil.putBoolean("login_laikan_setting", true);
                        BookShelfRequester.syncBookFromServer();
                        dao.distributionTask();
                        // 同步本地书架列表
                        SPUtil.putBoolean("isGetAssetsGift", false);
                        SPUtil.putBoolean("login_success", true);
                        finish();
                    }else {
                        ToastMgr.showShortToast(obj.getString("error_msg"));
                    }
                }catch (JSONException e) {
                    e.printStackTrace();
                    ToastMgr.showShortToast(R.string.laikan_data_load_failed);
                }finally {


                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                mloadingDialog.dismiss();
                reqLogin++;
                if (reqLogin <= 3) {
                    UserLogin();
                }
                ToastMgr.showShortToast(R.string.laikan_network_anomaly);
            }

            @Override
            public void onFinish() {

            }
        };

        Requester requester = new Requester();
        requester.setUrl(APIProtocol.laikan_login);
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);

//        HttpApiRequestEngine.getInstance().httpPostRequest(APIProtocol.laikan_login, map, null, null, requestListener);
    }

    public class CountDownTimerUtils extends CountDownTimer {

        private TextView mTextView;
        private SpannableString spannableString;
        ForegroundColorSpan span, span1;

        /**
         * @param millisInFuture The number of millis in the future from the call
         * to {@link #start()} until the countdown is done and {@link #onFinish()}
         * is called.
         * @param countDownInterval The interval along the way to receive
         * {@link #onTick(long)} callbacks.
         */
        public CountDownTimerUtils(TextView textView, long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
            this.mTextView = textView;
        }

        @Override
        public void onTick(long millisUntilFinished) {
            mTextView.setClickable(false);
            mTextView.setText(millisUntilFinished / 1000 + " 秒后 重新发送");
            spannableString = new SpannableString(mTextView.getText().toString());
            span = new ForegroundColorSpan(Color.parseColor("#FFFFFF"));
            span1 = new ForegroundColorSpan(Color.parseColor("#FFFFFF"));
            spannableString.setSpan(span, 0, 2, SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);
            spannableString.setSpan(span1, 2, spannableString.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            mTextView.setText(spannableString);
        }

        @Override
        public void onFinish() {
            mTextView.setClickable(true);
            mTextView.setText("获取验证码");
            mTextView.setTextColor(Color.parseColor("#FFFFFF"));
        }
    }

}

